<template>
  <div ref="boxRef" class="container"></div>
</template>

<script setup>
import {
  Scene,
  PerspectiveCamera,
  WebGLRenderer,
  BoxGeometry,
  MeshLambertMaterial,
  Mesh,
  PointLight,
  Color,
} from "three";
import { ref, onMounted, onUnmounted } from "vue";

let boxRef = ref(null);
let scene, camera, renderer, mesh;
let animationFrameId;

onMounted(() => {
  initThree();
  animate();
});

onUnmounted(() => {
  cancelAnimationFrame(animationFrameId);
  if (renderer) {
    renderer.dispose();
  }
  window.removeEventListener("resize", onWindowResize);
});

// 初始化
const initThree = () => {
  scene = new Scene();

  // 创建几何体
  const geometry = new BoxGeometry(100, 100, 100);
  const material = new MeshLambertMaterial({
    color: new Color("orange"),
  });
  mesh = new Mesh(geometry, material);
  mesh.position.set(0, 0, 0);
  scene.add(mesh);

  // 创建光源
  const pointLight = new PointLight(0xffffff, 10000);
  pointLight.position.set(80, 80, 80);
  scene.add(pointLight);

  // 获取容器尺寸
  const container = boxRef.value;
  const width = container.clientWidth || window.innerWidth;
  const height = container.clientHeight || window.innerHeight;

  // 创建相机
  camera = new PerspectiveCamera(60, width / height, 0.1, 1000);
  camera.position.set(200, 200, 200);
  camera.lookAt(0, 0, 0);

  // 创建渲染器
  renderer = new WebGLRenderer({
    alpha: true,
    antialias: true,
    powerPreference: "high-performance",
  });
  renderer.setSize(width, height);

  container.appendChild(renderer.domElement);

  window.addEventListener("resize", onWindowResize);
};

// 动画
const animate = () => {
  animationFrameId = requestAnimationFrame(animate);
  // mesh.rotation.x += 0.01
  // mesh.rotation.y += 0.01
  renderer.render(scene, camera);
};

// 窗口大小变化时，更新相机和渲染器
const onWindowResize = () => {
  if (!boxRef.value) return;

  const container = boxRef.value;
  const width = container.clientWidth || window.innerWidth;
  const height = container.clientHeight || window.innerHeight;

  if (!camera || !renderer) return;

  camera.aspect = width / height;
  camera.updateProjectionMatrix();

  renderer.setSize(width, height);
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
